using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;
using StupidSpaceThing;


namespace RacerGame
{
	internal abstract class Unit : FactionEntity
	{
		protected float turnSpeed = 0.01f;
		protected Vector2 lastForce = new Vector2(0,-1);		

		public Unit(FlyingEntity entity)
			: base(entity) {			
		}

		public virtual void ApplyForce(Vector2 force, bool ignoreDirection) {
			if( ignoreDirection ) {
				((FlyingEntity)entity).ApplyForce(force);
				return;
			}
			float forceLength = force.Length();
			if( forceLength == 0 ) return;
			Vector2 curForce = Vector2.Normalize(force);
			curForce = new Vector2(MathHelper.Clamp(curForce.X, lastForce.X - turnSpeed, lastForce.X + turnSpeed), MathHelper.Clamp(curForce.Y, lastForce.Y - turnSpeed, lastForce.Y + turnSpeed));
			((FlyingEntity)entity).ApplyForce(curForce * forceLength);
			lastForce = curForce;
		}
		public void ApplyForce(Vector2 destination, float force) {
			Vector2 direction = destination - Position2D;
			direction.Normalize();
			ApplyForce(direction * force, false);
		}

		public override void Update(RealGameTime gameTime) {
			if( Collision && !Entity.Dead ) {
				if( ((FlyingEntity)entity).OccupiedCell != null ) {
					((FlyingEntity)entity).OccupiedCell.Occupier = null;
				}
				((FlyingEntity)entity).OccupiedCell = RacerGame.CurMap.Occupy(this);
			}
			((FlyingEntity)entity).Update(gameTime);
			AudioEmitter.Position = Position;
			if( Collision ) {
				AudioEmitter.Velocity = Entity.ColObject.LinearVelocity;
			}
			base.Update(gameTime);
		}
	}
}
